#pragma once 

#include <iostream>
#include <string>
#include <functional>
#include "Inetaddr.hpp"

class Reactor;
// class Connection;

// using func_t = std::function<void(std::shared_ptr<Connection>)>;

class Connection
{
public:
    Connection()
        : _sockfd(-1)
        , _events(-1)
    {}

    void SetSockfd(int sockfd)
    {
        _sockfd = sockfd;
    }

    void SetPeerInfo(const InetAddr& peer_addr)
    {
        _peer_addr = peer_addr;
    }

    void SetEvents(uint32_t events) { _events = events; }

    uint32_t GetEvents() { return _events; }

    int Sockfd() { return _sockfd; }

    void SetOwner(Reactor* owner)
    {
        _owner = owner;
    }

    void Close()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

    Reactor* GetOwner() { return _owner; }

    // 把收到的数据添加到自己的接收缓冲区
    void Append2In(const std::string &in) { _inbuffer += in; }
    void Append2Out(const std::string &out) { _outbuffer += out; }
    std::string &OutBuffer() { return _outbuffer; }
    std::string &InBuffer() { return _inbuffer; }
    void DisCardOutBuffer(int n) { _outbuffer.erase(0, n); }
    bool IsOutBufferEmpty() { return _outbuffer.empty(); }

    virtual void Recver() = 0;
    virtual void Sender() = 0;
    virtual void Excepter() = 0;

    ~Connection()
    {}
private:
    int _sockfd;
    std::string _inbuffer;
    std::string _outbuffer;
    InetAddr _peer_addr; // 客户端信息

    Reactor* _owner; // 在其派生类中使用基类指针操作

    uint32_t _events; // 这个connection关心的事件
};

// class Factory
// {
// public:
//     // 静态成员函数实现工厂方法
//     static std::shared_ptr<Connection> BuildConnection(int fd, uint32_t events, func_t r, func_t s, func_t e)
//     {
//         auto conn = std::make_shared<Connection>(fd);
//         conn->SetEvents(events);
//         conn->InitCB(r, s, e);
//         return conn;
//     }
// };